<!--
 * @Author: yaolunmao
-->
<template>
  <div class="rightNav" :style="'max-height:' + ($store.state.windowAttributes.height + 300) + 'px'">
    <a-tabs type="card" v-model:activeKey="tabsKey" class="components-layout-right" @change="changeTabs">
      <a-tab-pane key="1" tab="属性">
        <a-collapse
          v-model:activeKey="attributeCollapseKey"
          @click.stop="clickGroup({ groupItem, componentItem })"
          expand-icon-position="right"
        >
          <a-collapse-panel key="1_1" header="属性设置">
            <div
              class="attribute"
              :style="'max-height:' + ($store.state.windowAttributes.height + 80) + 'px'"
              v-if="selectSvgInfo"
            >
              <a-form :labelCol="{ span: 8 }" :wrapperCol="{ span: 14 }">
                <a-form-item label="类型" v-if="selectSvgInfo.createType || selectSvgInfo.imgType">
                  <p>{{ create_type[selectSvgInfo.createType] }}({{ selectSvgInfo.imgType }})</p>
                </a-form-item>
                <a-form-item label="名称">
                  <a-input v-model:value="selectSvgInfo.title" placeholder="请输入组件名称" />
                </a-form-item>
                <a-form-item label="X轴坐标">
                  <a-input-number v-model:value="selectSvgInfo.svgPositionX" :min="0" :max="1920" />
                </a-form-item>
                <a-form-item label="Y轴坐标">
                  <a-input-number v-model:value="selectSvgInfo.svgPositionY" :min="0" :max="1080" />
                </a-form-item>
                <a-form-item label="大小">
                  <a-input-number v-model:value="selectSvgInfo.size" :min="1" :max="3000" step="0.1" />
                </a-form-item>
                <a-form-item label="旋转">
                  <a-input-number v-model:value="selectSvgInfo.angle" :min="0" :max="360" />
                </a-form-item>
                <!-- 自定义属性 -->
                <default-attribute style="padding: 5px 10px" :defaultAttribute="selectSvgInfo.defaultAttr" />
              </a-form>
            </div>
            <a-empty v-else description="暂无组件信息哦~" />
          </a-collapse-panel>
        </a-collapse>
      </a-tab-pane>
      <a-tab-pane key="2" tab="分组">
        <a-spin :spinning="spinning">
          <a-collapse v-model:activeKey="groupCollapseKey" accordion expand-icon-position="right">
            <a-collapse-panel key="2_1" header="事件分组">
              <group-components
                :popGroupIndex="0"
                :popComponentIndex="0"
                :groupLists="groupLists"
                :selectTemplateSvg="selectTemplateSvg"
                :fatherGroupItem="groupList[0]"
                @addGroupMethod="addGroupMethod"
                @clickGroup="clickGroup"
                @handleMenu="handleMenu"
                @inputBlur="inputBlur"
              />
              <div class="button" v-if="groupLists[0]?.componentsList">
                <!-- <div class="button"> -->
                <a-button type="primary" @click.stop="submitGroup(templateId)">保存</a-button>
              </div>
            </a-collapse-panel>
          </a-collapse>
        </a-spin>
      </a-tab-pane>
      <a-tab-pane key="3" tab="数据">
        <a-form class="aForm">
          <a-form-item style="width: 260px" :labelCol="{ span: 7 }" colon label="类型">
            <a-select
              placeholder="请选择关联的类型"
              allowClear
              v-model:value="selectSvgInfo.componentDataSource"
              :getPopupContainer="(triggerNode) => triggerNode.parentNode"
              style="width: 180px"
            >
              <a-select-option v-for="item in component_data_source" :key="item" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item colon :labelCol="{ span: 6 }" label="数值KEY">
            <div class="formItem">
              <a-input
                placeholder="请选择关联数值KEY"
                v-model:value="selectSvgInfo.dataKeyValue"
                style="width: 180px"
                :disabled="true"
              >
                <template #suffix v-if="selectSvgInfo.dataKeyValue">
                  <close-circle-outlined @click="deleteValue('dataKey')" style="color: rgba(0, 0, 0, 0.45); cursor: pointer" />
                </template>
              </a-input>
              <switcher-filled
                @click="openSelectKeyModal('数值KEY', 'dataKey')"
                style="font-size: 25px; margin: 2px 0 0 5px; color: rgb(24, 144, 255)"
              />
            </div>
          </a-form-item>
          <a-form-item colon :labelCol="{ span: 6 }" label="状态KEY">
            <div class="formItem">
              <a-input
                placeholder="请选择关联状态KEY"
                v-model:value="selectSvgInfo.stateKeyValue"
                style="width: 180px"
                :disabled="true"
              >
                <template #suffix v-if="selectSvgInfo.stateKeyValue">
                  <close-circle-outlined @click="deleteValue('stateKey')" style="color: rgba(0, 0, 0, 0.45); cursor: pointer" />
                </template>
              </a-input>
              <switcher-filled
                @click="openSelectKeyModal('状态KEY', 'stateKey')"
                style="font-size: 25px; margin: 2px 0 0 5px; color: rgb(24, 144, 255)"
              />
            </div>
          </a-form-item>
        </a-form>
      </a-tab-pane>
    </a-tabs>
  </div>
  <!--绑定key-->
  <ant-modal
    :visible="modal.visible"
    :title="modal.title"
    :getContainer="getPopupContainer"
    :width="isFullscreen ? 1800 : 1200"
    @cancelModal="cancelAddGroupModal"
  >
    <slot>
      <key-lists @bindKey="bindKey" />
    </slot>
  </ant-modal>

  <!--是否保存分组-->
  <ant-modal
    :visible="saveGroupTipsVisible"
    :title="'温磬提示'"
    :getContainer="getPopupContainer"
    :width="600"
    @cancelModal="cancelAddGroupModal"
  >
    当前有未保存分组，是否保存？
    <div style="display: flex; text-align: center; margin: 40px auto">
      <div style="flex: 1">
        <a-button @click="cancelAddGroupModal">取消</a-button>
      </div>
      <div style="flex: 1">
        <a-button type="primary" @click="submitGroup('', 'hideConfig')">保存</a-button>
      </div>
    </div>
  </ant-modal>
</template>
<script>
import { message } from 'ant-design-vue'
import defaultAttribute from '@/components/svgComponents/defaultAttribute.vue'
import groupComponents from '@/components/svgComponents/groupComponents.vue'
import keyLists from '@/components/svgComponents/keyLists.vue'
import { SwitcherFilled, CloseCircleOutlined } from '@ant-design/icons-vue'
import { toParse, aimToArr, toStringify } from '@/util'
import { addGroup, listEventGroup, generalDict, keyRuleDefineLazyLoad } from '@/network/api'
import antModal from '../../common/antComponents/antModal.vue'
export default {
  emits: ['changeSelectTemplateSvg', 'changeTemplateSvgListsStatus', 'createTemplate'],
  props: ['selectTemplateSvg', 'templateId'],
  inject: ['getScreenFullNode', 'getScreenStatus'],
  components: {
    groupComponents,
    SwitcherFilled,
    CloseCircleOutlined,
    defaultAttribute,
    antModal,
    keyLists,
  },
  data() {
    return {
      modal: {
        dataType: '', //key类型名称
        title: '',
        visible: false,
      },
      isEditGroup: false,
      component_data_source: {}, //操作类型
      create_type: {
        draggable: '拖拽式',
        draw: '绘制式',
      },
      saveGroupTipsVisible: false,
      spinning: false,
      tabsKey: '1',
      groupList: [],
      groupLists: [],
      attributeCollapseKey: ['1_1'],
      groupCollapseKey: ['2_1'],
      //基础分组
      baseGroups: {
        //-------前端数据--------------------//
        isAddStatus: true, //当前组是否可增加组件 || 子组状态
        collpaseStatus: true, //当前组的收缩状态
        editStatus: false, //分组标题编辑状态
        activeTabsKey: 'openValve', //当前组的activeKey
        menusConfig: [
          {
            name: '添加下级分组',
            type: 'group',
          },
          {
            name: '移除分组',
            type: 'group',
          },
        ],
        //---------------------------------//
      },
      currentSelectSvg: {},
      valueOptions: [],
      loadData: null,
      dataFormKey: {
        typeKey: null,
        valueKey: null,
        statusKey: null,
      },
      columns: [
        {
          title: 'Name',
          dataIndex: 'name',
          sorter: true,
          width: '20%',
        },
        {
          title: 'Gender',
          dataIndex: 'gender',
          filters: [
            { text: 'Male', value: 'male' },
            { text: 'Female', value: 'female' },
          ],
          width: '20%',
        },
        {
          title: 'Email',
          dataIndex: 'email',
        },
        {
          title: 'Name',
          dataIndex: 'name',
          sorter: true,
          width: '20%',
        },
        {
          title: 'Gender',
          dataIndex: 'gender',
          filters: [
            { text: 'Male', value: 'male' },
            { text: 'Female', value: 'female' },
          ],
          width: '20%',
        },
        {
          title: 'Email',
          dataIndex: 'email',
        },
      ],
    }
  },
  mounted() {
    this.getDict()
    // 监听父页面向子页面的传参
    // window.addEventListener('message', (e) => {
    //   e.data.data ? this.iframeEvent(e.data) : '';
    // });
  },
  computed: {
    isFullscreen() {
      return this.getScreenStatus()
    },
    getPopupContainer() {
      return this.getScreenFullNode()
    },
    selectSvgInfo() {
      return this.selectTemplateSvg
    },
  },
  watch: {
    // 'selectSvgInfo.tableRowCount': function (newVal) {
    //   this.$emit(
    //     'setTableAttr',
    //     this.selectSvgInfo.componentDataId,
    //     newVal,
    //     this.selectSvgInfo.tableColCount
    //   );
    // },
    // 'selectSvgInfo.tableColCount': function (newVal) {
    //   this.$emit(
    //     'setTableAttr',
    //     this.selectSvgInfo.componentDataId,
    //     this.selectSvgInfo.tableRowCount,
    //     newVal
    //   );
    // },
    selectTemplateSvg: {
      deep: true,
      immediate: true,
      handler(val) {
        val.type == 'WaterPipeValveSvg' ? this.recursionFindActiveGroup(this.groupLists) : ''
        JSON.stringify(val) != '{}' && val ? this.addComponent(val) : ''
      },
    },
  },
  methods: {
    checkGroupStatus() {
      this.isEditGroup
        ? this.cancelAddGroupModal()
        : this.$store.setconfigPanalStatusVal(!this.$store.state.configPanalStatus.right, 'right')
    },
    cancelAddGroupModal() {
      // this.modal.visible = !this.modal.visible
      // this.saveGroupTipsVisible = !this.saveGroupTipsVisible;
    },
    bindKey(record) {
      this.selectSvgInfo[`${this.modal.dataType}Id`] = record.keyValue
      this.selectSvgInfo[`${this.modal.dataType}Value`] = record.keyName
      this.modal = {
        dataType: '',
        title: '',
        visible: !this.modal.visible,
      }
    },
    openSelectKeyModal(title, dataType) {
      if (JSON.stringify(this.selectSvgInfo) != '{}' && this.selectSvgInfo) {
        this.modal = {
          dataType: dataType,
          title: title,
          visible: !this.modal.visible,
        }
      } else {
        message.warning('当前暂无选中组件')
      }
    },
    cancelModal() {
      this.modal.visible = !this.modal.visible
    },
    deleteValue(val) {
      switch (val) {
        case 'dataKey':
          this.selectSvgInfo.dataKeyValue = ''
          this.selectSvgInfo.dataKeyId = ''
          break
        case 'stateKey':
          this.selectSvgInfo.stateKeyValue = ''
          this.selectSvgInfo.stateKeyId = ''
          break
        default: {
        }
      }
    },
    getKeyRuleDefineLazyLoad(targetOption = { id: '' }, selectedOptions) {
      targetOption.loading = true
      let params = { id: targetOption.id }
      //不要问第4次才加id进行组合查询，要问就问后端
      selectedOptions?.length >= 4
        ? Object.assign(params, {
            typeId: selectedOptions[0]?.id,
            registerId: selectedOptions[1]?.id,
            registerSubtypeId: selectedOptions[2]?.id,
            crewId: selectedOptions[3]?.id,
            childId: selectedOptions[4]?.id,
          })
        : ''

      this.$httpRequest(keyRuleDefineLazyLoad, params)
        .then((res) => {
          res.data.forEach((item) => {
            item.isLeaf = !item.isSubordinate
          })
          if (targetOption.id) {
            targetOption.children = res.data
            this.valueOptions = [...this.valueOptions]
          } else {
            this.valueOptions = res.data
          }
          targetOption.loading = false
        })
        .catch(() => {
          targetOption.loading = false
        })
    },
    //add group
    addGroupMethod(list) {
      // 开关类组件才能创建相关组(改变增加组按钮的状态)
      switch (this.selectTemplateSvg.type) {
        case 'WaterPipeValveSvg':
          list.push(
            JSON.parse(
              JSON.stringify(
                Object.assign(this.baseGroups, {
                  componentsList: [], //组件
                  groupLists: [], //子分组
                  type: this.selectTemplateSvg.type,
                  componentDataId: this.selectTemplateSvg.componentDataId,
                  title: this.selectTemplateSvg.title,
                })
              )
            )
          )
          this.chengeAddGroupButtonStatus(this.selectTemplateSvg, true, list[0])
          this.isEditGroup = true
          break
        default:
          message.warning('创建相关组,请选择开关类组件哦~')
          break
      }
    },
    //点击分组 || 点击分组组件
    clickGroup(clickItem) {
      if (clickItem?.componentItem?.componentDataId == this.selectTemplateSvg.componentDataId) return
      let resetActive = (list) => {
        list.forEach((item) => {
          clickItem.componentItem ? (item.isAddStatus = true) : ''
          item.isAddStatus = clickItem.groupItem.componentDataId == item.componentDataId ? true : false
          item.groupLists ? resetActive(item.groupLists) : ''
        })
      }
      //点击子组件，重置其他组状态
      resetActive(this.groupLists)
      //子组件互联状态
      clickItem?.componentItem ? this.$emit('changeSelectTemplateSvg', clickItem.componentItem) : ''
    },
    //click menus
    handleMenu(val) {
      this.isEditGroup = true
      switch (val.key) {
        case 0:
          //当前组的组件不能被重复创建(同级 || 下级)
          val.value1.componentDataId != this.selectTemplateSvg.componentDataId ? this.addGroupMethod(val.value1.groupLists) : ''
          break
        case 1:
          val.type == 'group' ? this.chengeAddGroupButtonStatus(this.selectTemplateSvg, false, val.value1[0]) : ''
          val.value1.splice(val.value2, 1)
          //清空当前分组
          if (this.groupLists.length == 0) {
            this.submitGroup()
          }
          break
      }
    },
    resetGroup() {
      this.groupLists = []
    },
    getDict() {
      this.$httpRequest(generalDict, {
        dictType: 'component_data_source',
      }).then((res) => {
        this.component_data_source = aimToArr(res)
      })
    },
    //input blur event
    inputBlur(val) {
      val.editStatus = !val.editStatus
      !val.title ? (val.title = this.selectSvgInfo.title) : ''
    },
    //保存分组
    submitGroup(templateId, type = 'submitGroup') {
      if (this.templateId || templateId) {
        this.spinning = true
        //全部自定义属性改成string
        this.groupLists ? toStringify(this.groupLists) : ''
        this.groupLists.length && type != 'submitTemplate' ? this.$emit('createTemplate') : ''
        this.$httpRequest(
          addGroup,
          {
            addEventGroupDetailForm: this.groupLists,
            waterTemplateId: this.templateId || templateId,
          },
          'post'
        )
          .then(() => {
            type == 'submitGroup' ? message.success('保存分组成功~') : ''
            toParse(this.groupLists)
            this.isEditGroup = false
            this.saveGroupTipsVisible = false
            this.spinning = false
            type == 'hideConfig' ? this.$store.setconfigPanalStatusVal(!this.$store.state.configPanalStatus.right, 'right') : ''
          })
          .catch(() => {
            this.spinning = false
          })
      } else {
        message.warning('请保存当前模板哦~')
      }
    },
    //递归查找active group
    recursionFindActiveGroup(list) {
      list.length
        ? list.forEach((item) => {
            if (item.componentDataId == this.selectTemplateSvg.componentDataId) {
              item.isAddStatus = true
              item.groupLists ? this.recursionFindActiveGroup(item.groupLists) : ''
            } else {
              item.isAddStatus = false
              item.groupLists ? this.recursionFindActiveGroup(item.groupLists) : ''
            }
          })
        : ''
    },
    //show or hide add group button
    chengeAddGroupButtonStatus(obj, val, list) {
      obj.hideAddGroup = val
      list.hideAddGroup = val
      let deleteComponentsArr = []
      deleteComponentsArr.push({
        componentDataId: list.componentDataId,
        hideAddGroup: list.hideAddGroup,
      })
      let resetAddGroupStatus = (list) => {
        list.forEach((item) => {
          item.hideAddGroup = val
          //取出当前子分组的状态,改变源数据的状态（组件是否可增加分组）
          deleteComponentsArr.push({
            componentDataId: item.componentDataId,
            hideAddGroup: item.hideAddGroup,
          })
          item.groupLists ? resetAddGroupStatus(item.groupLists) : ''
        })
      }
      list.groupLists ? resetAddGroupStatus(list.groupLists) : ''
      deleteComponentsArr ? this.$emit('changeTemplateSvgListsStatus', deleteComponentsArr) : ''
    },
    //active group push components
    addComponent(val) {
      let addModel
      switch (val.type) {
        case 'WaterPipeValveSvg':
          break
        default:
          addModel = (list) => {
            //逻辑1 => 当前组件只能存在一个分组里面(子分组和同级分组同时存在时，有点小问题)
            // list
            //   ? list.forEach((item) => {
            //       if (
            //         item.isAddStatus &&
            //         item.componentDataId != val.componentDataId
            //       ) {
            //         console.log(this.searchGroupListsSurviveCompoennt(val));
            //         if (!this.searchGroupListsSurviveCompoennt(val)) {
            //           item.componentsList.push({
            //             componentDataId: val.componentDataId,
            //             title: val.title,

            //             collpaseStatus: false, //组件属性收缩状态
            //             editStatus: false, //分组标题编辑状态
            //             menusConfig: [
            //               {
            //                 name: '移除组件',
            //                 type: 'group',
            //               },
            //             ],
            //             defaultAttr: {},
            //           });
            //           console.log(item.componentsList);
            //         }
            //       } else {
            //         item.groupLists ? addModel(item.groupLists) : '';
            //       }
            //     })

            //   : '';

            //逻辑2 => 组件可以同时存在不同的组(子组、同级组等等)
            list
              ? list.forEach((item) => {
                  if (
                    item.isAddStatus &&
                    !item.componentsList.filter((componentItem) => {
                      return componentItem.componentDataId == val.componentDataId
                    }).length
                  ) {
                    item.componentsList.push({
                      componentDataId: val.componentDataId,
                      title: val.title,
                      //阀门开启 && 关闭状态
                      openValve: JSON.parse(JSON.stringify(val.defaultAttr)),
                      closeValve: JSON.parse(JSON.stringify(val.defaultAttr)),

                      collpaseStatus: false, //组件属性收缩状态
                      editStatus: false, //分组标题编辑状态
                      menusConfig: [
                        {
                          name: '移除组件',
                          type: 'group',
                        },
                      ],
                      size: val.size,
                      svgPositionX: val.svgPositionX,
                      svgPositionY: val.svgPositionY,
                      angle: val.angle,
                      type: val.type,
                    })
                    this.isEditGroup = true
                  }
                  item.groupLists ? addModel(item.groupLists) : ''
                })
              : ''
          }
          addModel(this.groupLists)
          break
      }
    },
    //查询当前分组是否存在当前组件
    searchGroupListsSurviveCompoennt(component) {
      let flage
      let searchComponents = (list) => {
        try {
          list.forEach((groupItem) => {
            if (groupItem.componentDataId == component.componentDataId) {
              throw new Error(true)
            } else {
              flage = false
            }
            groupItem.componentsList.length
              ? groupItem.componentsList.forEach((componentItem) => {
                  if (componentItem.componentDataId == component.componentDataId) {
                    throw new Error(true)
                  } else {
                    flage = false
                  }
                })
              : ''
            groupItem.groupLists.length ? searchComponents(groupItem.groupLists) : ''
          })
        } catch (err) {
          flage = err.message
        }
      }
      searchComponents(this.groupLists)
      return flage
    },
    //查询分组
    getTemplateGroup(id) {
      this.groupLists = []
      this.spinning = true
      this.$httpRequest(listEventGroup, { waterTemplateId: id })
        .then((res) => {
          const groupLists = res.data
          if (groupLists) {
            let addAttribute = (list) => {
              list.forEach((item) => {
                //增加分组操作
                Object.assign(item, {
                  isAddStatus: true, //当前组是否可增加组件 || 子组状态
                  collpaseStatus: true, //当前组的收缩状态
                  editStatus: false, //分组标题编辑状态
                  activeTabsKey: 'openValve', //当前组的activeKey
                  menusConfig: [
                    {
                      name: '添加下级分组',
                      type: 'group',
                    },
                    {
                      name: '移除分组',
                      type: 'group',
                    },
                  ],
                })
                //已分组重置按钮状态
                item.hideAddGroup = false
                item.componentsList
                  ? item.componentsList.forEach((componentItem) => {
                      //增加组件操作
                      componentItem.menusConfig = [
                        {
                          name: '移除组件',
                          type: 'group',
                        },
                      ]
                    })
                  : (item.componentsList = [])
                item.groupLists ? addAttribute(item.groupLists) : (item.groupLists = [])
              })
            }
            addAttribute(groupLists)
            toParse(groupLists)
            //回显
            this.groupLists = groupLists
            this.recursionFindActiveGroup(this.groupLists)
            this.spinning = false
          } else {
            this.spinning = false
          }
        })
        .catch(() => {
          this.spinning = false
        })
    },
    changeTabs(activeKey) {
      if (this.templateId) {
        activeKey == 2 && this.groupLists.length == 0 ? this.getTemplateGroup(this.templateId) : ''
      }
    },
  },
}
</script>
<style scoped lang="less">
::-webkit-scrollbar {
  width: 6px;
  height: 5px;
}
::-webkit-scrollbar-track {
  border-radius: 10px;
  background-color: #f2f2f2;
}

::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background-color: #9e9e9e;
}
.components-layout-right {
  .ant-tabs-bar {
    margin-bottom: 0 !important;
  }

  .ant-form-item-label {
    width: 100px !important;
    flex-shrink: 0;
  }

  .ant-input-number,
  input {
    width: 160px;
    border-radius: 4px;
    border-color: #ddd;
  }

  .ant-form-item-control {
    line-height: 24px !important;

    p {
      margin-bottom: 0 !important;
    }
  }

  .ant-form-item {
    display: flex;
    align-items: center;
    flex-flow: nowrap;
    position: relative;
    margin-bottom: 0;
    padding: 5px 10px;

    &:after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 15px;
      right: 15px;
      bottom: 0;
      height: 1px;
    }

    &:last-child::after {
      content: unset;
    }
  }
  .aForm {
    height: 50vh;
    .formItem {
      .tab {
        padding: 5px;
        color: black;
        z-index: 9999999999999999;
      }
    }
  }
}

/deep/ .vc-color-wrap {
  width: 100%;
}

.formItem {
  display: flex;
}

.attribute {
  overflow: auto;
  height: 100%;
}

.btn-sure {
  width: 260px;
  margin: 20px;
}

.bg-code {
  background: #444;
  color: #fff;
  width: calc(100% - 20px);
  margin: 20px 10px;
  border-radius: 4px;
  padding: 10px;
}

.rightNav {
  right: 0;
  top: 0;
  bottom: 0;
  min-width: unset !important;
  max-width: unset !important;
  width: 300px !important;
  height: 100%;
  z-index: 1;
  overflow: auto;
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
  -ms-user-select: none;
}

.button {
  margin: 10px;
  text-align: center;
}
/deep/ .ant-collapse-content > .ant-collapse-content-box {
  padding: 0px !important;
}
</style>
